#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkInterface>
#include <QHostInfo>
#include <QThread>
#include <QDebug>
#include <QFileDialog>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), socket_desc(-1), socket_work(nullptr),
    sendMegcls("file")
{

    ui->setupUi(this);
    qRegisterMetaType<qintptr>("qintptr");

    tcp_server = new ThreadTcpServer(this);
    connect(tcp_server, &ThreadTcpServer::new_connection, this, &MainWindow::process_new_connect_slot);
    connect(ui->CB_Mecls, SIGNAL(currentIndexChanged(QString)), this,  SLOT(slot_ComboxChange(QString)));


    ui->CB_Mecls->addItem("file");
    ui->CB_Mecls->addItem("picture");

//    setFixedSize(QSize(1000, 800));
    setAutoFillBackground(true);
    ui->Btn_SystemInit->setEnabled(true);

    ui->Btn_selectPath->setEnabled(false);
    ui->Btn_TCPSendMeg->setEnabled(false);
    ui->Btn_UDPSendMeg->setEnabled(false);

    ui->Edit_showPath->setEnabled(false);
    ui->Edit_StringMeg->setEnabled(false);
    ui->Btn_send->setEnabled(false);

    ui->Btn_OpenTCPServer->setEnabled(false);
    ui->Btn_CloseTCPServer->setEnabled(false);
    ui->Btn_getClientIP->setEnabled(false);

    qRegisterMetaType<qintptr>("qintptr");
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::process_new_connect_slot(qintptr socketDescriptor)
{
    ui->textBrowser->append("Client connect, socketDescriptor: " + QString::number(socketDescriptor));

    socket_work = new SocketWork(socketDescriptor);
    socket_desc = socketDescriptor;

    QThread *socket_thread = new QThread;


    socket_work->moveToThread(socket_thread);

    connect(this, &MainWindow::disconnect_socket_signal, socket_work, &SocketWork::disconnect_socket_slot);
    connect(this, &MainWindow::send_TcpMessage_signal, socket_work, &SocketWork::send_Message_slot);
    connect(this, &MainWindow::send_File_signal, socket_work, &SocketWork::send_file_slot);
    connect(this, &MainWindow::send_Pic_signal, socket_work, &SocketWork::send_file_slot);
    connect(this, &MainWindow::Update_IP_signal, socket_work, &SocketWork::Update_IP_slot);
    connect(socket_work, &SocketWork::preview_image_signal, this, &MainWindow::preview_image_slot);

    connect(socket_work, &SocketWork::update_textBrowser_signal, this,  [=](QString meg){

        ui->textBrowser->append(meg);
    });

    connect(socket_thread, &QThread::finished, socket_work, &QThread::deleteLater);
    connect(socket_thread, &QThread::finished, socket_thread, &QThread::deleteLater);

    connect(socket_work, &SocketWork::receive_data_signal, this, [=](qintptr desc_ptr, const QByteArray &data) {
        ui->textBrowser->append(QString::number(desc_ptr) + ": " + data);
    });

    connect(socket_work, &SocketWork::disconnect_socket_signal, this, [=](qintptr desc_ptr) {
        socket_thread->quit();
        socket_thread->wait();

        socket_desc = -1;
        ui->textBrowser->append("Client disconnect, socketDescriptor: " + QString::number(desc_ptr));

    });

    socket_thread->start();
    ui->Btn_TCPSendMeg->setEnabled(true);
}

void MainWindow::slot_ComboxChange(QString index)
{
    sendMegcls = index;
    qDebug() << "选中的选项索引是：" << index;
}

void MainWindow::on_Btn_send_clicked()
{
    if(sendMegcls == "file")
        sendFile();
    else if(sendMegcls == "picture")
        sendPic();
}

void MainWindow::on_Btn_selectPath_clicked()
{
    QString filename;
    filename = QFileDialog::getOpenFileName(this,tr("Select nii or obj 文件"),"",tr("*.nii;; *.Nii;; *.NII;; *.obj;; all(*)"));
    if(filename.isEmpty())
        qDebug() << "fileName is empty !";
    else
    {
        ui->Edit_showPath->setText(filename);
        ui->Btn_send->setEnabled(true);
    }

}

void MainWindow::sendFile()
{
    QString filename = ui->Edit_showPath->text();
    if(filename.isEmpty())
        qDebug() << "fileName is empty !";
    else
        emit send_File_signal(socket_desc, filename);
}

void MainWindow::sendPic()
{
    QString filename = ui->Edit_showPath->text();
    if(filename.isEmpty())
        qDebug() << "fileName is empty !";
    else
        emit send_Pic_signal(socket_desc, filename);
}

bool MainWindow::GetLocalIP()
{
    QVector<QString> ipv4_vec;

    foreach (QHostAddress ptr, QNetworkInterface::allAddresses())
    {
        if (ptr.protocol() == QAbstractSocket::IPv4Protocol)
        {
            if (!ptr.isLoopback())
            {
                ipv4_vec.append(ptr.toString());
            }
        }
    }

    if (ipv4_vec.empty())
    {
        return false;
    }

    localIp = ipv4_vec.at(0);

    return true;
}

void MainWindow::UDP_init()
{
    udp_work = new UDPWork;
    udp_thread = new QThread;
    udp_work->moveToThread(udp_thread);
    connect(udp_thread, &QThread::finished, udp_work, &UDPWork::deleteLater);
    connect(udp_thread, &QThread::finished, udp_thread, &QThread::deleteLater);
    connect(udp_work, &UDPWork::update_textBrowser_signal, this, [=](QString meg) { ui->textBrowser->append(meg); });
    connect(udp_work, &UDPWork::detain_ClientIP_signal, this, &MainWindow::detain_ClientIP_slot);
    connect(udp_work, &UDPWork::preview_image_signal, this, &MainWindow::preview_image_slot);

    connect(this, &MainWindow::send_UdpMessage_signal, udp_work, &UDPWork::send_Message_slot);
    connect(this, &MainWindow::send_Broadcast_signal, udp_work, &UDPWork::send_Broadcast_slot);
    connect(this, &MainWindow::Update_IP_signal, udp_work, &UDPWork::Update_IP_slot);


    udp_thread->start();
    ui->textBrowser->append("udp init sucess");

    ui->Btn_getClientIP->setEnabled(true);
}

void MainWindow::detain_ClientIP_slot(QString ip)
{

    ui->textBrowser->append("get remote ip: " + ip);

    ui->Edit_showPath->setEnabled(true);
    ui->Edit_StringMeg->setEnabled(true);

    ui->Btn_selectPath->setEnabled(true);
    ui->Btn_OpenTCPServer->setEnabled(true);
    ui->Btn_UDPSendMeg->setEnabled(true);

//    ui->Btn_getClientIP->setEnabled(false);
}

void MainWindow::preview_image_slot(QPixmap pixmap)
{
    ui->ImgLab->setPixmap(pixmap);  // 将图片设置到 QLabel 上
    ui->ImgLab->setScaledContents(true);  // 允许图片缩放以适应 QLabel 大小

}

void MainWindow::on_Btn_SystemInit_clicked()
{
    ui->textBrowser->clear();
    if(!GetLocalIP())
    {
        ui->textBrowser->append("No IPv4 address.");
    }
    else
    {
        ui->textBrowser->append("Host IP: " + localIp);
        UDP_init();
        ui->Btn_SystemInit->setEnabled(false);
        emit Update_IP_signal(localIp);
    }


    ReadLoalPicAndShow();

}

void MainWindow::ReadLoalPicAndShow()
{
     ui->textBrowser->append("load pic success1");
    QFile file("C://Users//Administrator//Pictures//init.jpeg");
    ui->textBrowser->append("load pic success2");
     // 打开文件以进行读取操作
     if (file.open(QIODevice::ReadOnly))
     {
         ui->textBrowser->append("load pic success3");
         // 使用 QByteArray 来存储文件内容
         QByteArray byteArray = file.readAll();
         ui->textBrowser->append("load pic success4");
         // 关闭文件
         file.close();
         QPixmap pixmap;

         if (!pixmap.loadFromData(byteArray))
         {
             ui->textBrowser->append("load pic success5");
             ui->textBrowser->append(QString().number(byteArray.length()));
             return;
         }
         ui->textBrowser->append("load pic success6");
         ui->ImgLab->setPixmap(pixmap);  // 将图片设置到 QLabel 上
         ui->textBrowser->append("load pic success7");
         ui->ImgLab->setScaledContents(false);  // 允许图片缩放以适应 QLabel 大小
         ui->textBrowser->append("load pic success8");
     }
     else
     {
         ui->textBrowser->append("Cannot load pic");
     }
}

void MainWindow::on_Btn_OpenTCPServer_clicked()
{
    ui->textBrowser->append("Start Listening...");

    tcp_server->listen(QHostAddress(localIp), 24500);

    QString hostName = QHostInfo::localHostName();
    ui->textBrowser->append("Host Name: " + hostName);

    ui->textBrowser->append("Host IP: " + tcp_server->serverAddress().toString());
    ui->textBrowser->append("Host Port: " + QString::number(tcp_server->serverPort()));

    ui->Btn_OpenTCPServer->setEnabled(false);
    ui->Btn_CloseTCPServer->setEnabled(true);
}

void MainWindow::on_Btn_CloseTCPServer_clicked()
{
    if (socket_desc != -1 && socket_work != nullptr)
    {
        emit disconnect_socket_signal(socket_desc);
    }

    if (tcp_server != nullptr)
    {
        if (tcp_server->isListening())
        {
            tcp_server->close();
        }
    }

    ui->Btn_OpenTCPServer->setEnabled(true);
    ui->Btn_TCPSendMeg->setEnabled(false);
    ui->Btn_CloseTCPServer->setEnabled(false);
}

void MainWindow::on_Btn_TCPSendMeg_clicked()
{
   emit send_TcpMessage_signal(socket_desc, ui->Edit_StringMeg->text());
}

void MainWindow::on_Btn_UDPSendMeg_clicked()
{
    emit send_UdpMessage_signal(ui->Edit_StringMeg->text());
}

void MainWindow::on_Btn_getClientIP_clicked()
{
    emit send_Broadcast_signal();
}
